/*
 *	Yalala
 *	
 *	Copyright © MediaMonks B.V.
 *	All rights reserved.
 *	
 *	Redistribution and use in source and binary forms, with or without
 *	modification, are permitted provided that the following conditions are met:
 *	1. Redistributions of source code must retain the above copyright
 *	   notice, this list of conditions and the following disclaimer.
 *	2. Redistributions in binary form must reproduce the above copyright
 *	   notice, this list of conditions and the following disclaimer in the
 *	   documentation and/or other materials provided with the distribution.
 *	3. All advertising materials mentioning features or use of this software
 *	   must display the following acknowledgement:
 *	   This product includes software developed by MediaMonks B.V.
 *	4. Neither the name of MediaMonks B.V. nor the
 *	   names of its contributors may be used to endorse or promote products
 *	   derived from this software without specific prior written permission.
 *	
 *	THIS SOFTWARE IS PROVIDED BY MEDIAMONKS B.V. ''AS IS'' AND ANY
 *	EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 *	WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 *	DISCLAIMED. IN NO EVENT SHALL MEDIAMONKS B.V. BE LIABLE FOR ANY
 *	DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 *	(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 *	LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 *	ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 *	(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 *	SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *	
 */

package com.mediamonks.yalala.ui.table 
{
	import temple.ui.tooltip.ToolTip;
	import temple.data.Trivalent;
	import temple.ui.behaviors.textfield.TextFieldColorizer;
	import temple.utils.TimeUtils;

	import com.mediamonks.yalala.data.enum.CustomContextMenuItems;
	import com.mediamonks.yalala.data.enum.LevelColors;
	import com.mediamonks.yalala.data.vo.RowData;
	import com.mediamonks.yalala.ui.UIEvent;

	import flash.display.Shape;
	import flash.display.Sprite;
	import flash.events.ContextMenuEvent;
	import flash.events.MouseEvent;
	import flash.system.System;
	import flash.text.TextField;
	import flash.text.TextFieldAutoSize;
	import flash.text.TextFormat;
	import flash.ui.ContextMenu;
	import flash.ui.ContextMenuItem;

	/**
	 * @author Thijs Broerse
	 */
	public class Row extends Sprite
	{
		/**
		 * The maximum length (in characters) of the message. If the message is longer, it will be truncated.
		 */
		private static const _MAX_MESSAGE_LENGTH:uint = 200;
		
		private var _frameField:TextField;
		private var _timeField:TextField;
		private var _messageField:TextField;
		private var _messageFieldColor:TextFieldColorizer;
		private var _data:RowData;
		private var _icon:Shape;
		
		public function Row() 
		{
			init();
		}

		private function init():void 
		{
			var tf:TextFormat = new TextFormat();
			tf.bold = true;
			tf.font = "_sans";
			tf.size = 10;
			tf.color = 0x555555;

			_frameField = new TextField();
			_frameField.width = 22;
			_frameField.height = 18;
			_frameField.defaultTextFormat = tf;
			addChild(_frameField);
			
			tf.color = 0xCCCCCC;
			_timeField = new TextField();
			_timeField.x = _frameField.x + _frameField.width;
			_timeField.width = 60;
			_timeField.height = 18;
			_timeField.defaultTextFormat = tf;
			addChild(_timeField);

			tf.color = 0xDDDDDD;
			_messageField = new TextField();
			_messageField.x = _timeField.x + _timeField.width;
			_messageField.height = 18;
			_messageField.defaultTextFormat = tf;
			_messageField.multiline = false;
			_messageField.autoSize = TextFieldAutoSize.LEFT;
			addChild(_messageField);
			
			_messageFieldColor = new TextFieldColorizer(_messageField, 0xffffff, 0xffff00, 0x0000ff);
			
			_icon = new Shape();
			_icon.visible = false;
			addChild(_icon);
			
			contextMenu = new ContextMenu();
			var item:ContextMenuItem = new ContextMenuItem(CustomContextMenuItems.COPY_MESSAGE);
			item.addEventListener(ContextMenuEvent.MENU_ITEM_SELECT, handleContextMenuItemSelect);
			contextMenu.customItems.push(item);
		}

		public function get data():RowData
		{
			return _data;
		}

		public function set data(value:RowData):void 
		{
			if (_data == value && (!value || !value.status)) return;
			
			_data = value;
			
			if (value)
			{
				visible = true;
				
				if (!value.message.frame || !value.message.time)
				{
					_frameField.text = "";
				}
				else
				{
					var frame:String = String(value.message.frame % 1000);
					while (frame.length < 3) frame = "0" + frame;
					_frameField.text = frame;
				}
				
				_messageFieldColor.textColor = LevelColors.COLORS[value.message.level];
		
				// time
				if (value.message.time == 0)
				{
					_timeField.text = "";
				}
				else if (!isNaN(value.message.time)) 
				{
					_timeField.text = TimeUtils.formatTime(value.message.time);
				}
				else
				{
					_timeField.text = "--";
				}
				
				// message
				var s:String;
				
				if (value.message.text && value.message.text.length > _MAX_MESSAGE_LENGTH)
				{
					s = value.message.text.substr(0, _MAX_MESSAGE_LENGTH) + "...";
				}
				else if (value.message.text)
				{
					s = value.message.text;
				}
				else
				{
					s = "";
				}
				
				if (value.message.sender != null) s += "\t\t-- " + value.message.sender;
				
				if (value.message.senderId) s += " | id:" + value.message.senderId;
				if (value.message.stackTrace) s += " | " + value.message.stackTrace;
				
				_messageField.text = s;
				
				// reset selection
				if (_messageField.selectionBeginIndex || _messageField.selectionEndIndex)
				{
					_messageField.setSelection(0, 0);
				}
				
				_messageField.alpha = 1;
				if (value.status)
				{
					var charIndex:int = _data.message.text.indexOf("{");
					if (charIndex == -1) charIndex = _data.message.text.indexOf("[");
					
					_icon.x = _messageField.x + _messageField.getCharBoundaries(charIndex).x - 10;
					
					_icon.visible = true;
					_icon.graphics.clear();
					_icon.graphics.beginFill(LevelColors.COLORS[value.message.level], 0);
					_icon.graphics.drawRect(0, 0, 10, 20);
					_icon.graphics.endFill();
					_icon.graphics.beginFill(LevelColors.COLORS[value.message.level]);
					_icon.graphics.drawRect(2, 9, 5, 1);
					_icon.graphics.endFill();
					
					if (!value.isOpen)
					{
						_icon.graphics.beginFill(LevelColors.COLORS[value.message.level]);
						_icon.graphics.drawRect(4, 7, 1, 5);
						_icon.graphics.endFill();
						
						_messageField.appendText("..." + (_data.message.text.indexOf("{") == -1 ? "]" : "}"));
						_messageField.appendText("   (" + _data.children.length + " items)");
						_messageField.alpha = .3;
						ToolTip.add(this, "Click to expand");
					}
					else
					{
						ToolTip.add(this, "Click to collapse");
					}
					addEventListener(MouseEvent.CLICK, handleClick);
					mouseChildren = false;
					buttonMode = true;
				}
				else
				{
					_icon.visible = false;
					mouseChildren = true;
					buttonMode = false;
					removeEventListener(MouseEvent.CLICK, handleClick);
					ToolTip.remove(this);
				}
			}
			else
			{
				visible = false;
			}
		}

		public function highLight(text:String):void 
		{
			graphics.clear();
			
			if (_data && _data.highlighted)
			{
				graphics.beginFill(0x222222);
				graphics.drawRect(0, 1, 4000, 14);
				graphics.endFill();
			}
			
			if (!text) return;
			
			graphics.beginFill(0xffff00, .1);
			graphics.lineStyle(1, 0xffff00, .8);
			
			var offset:uint;
			var index:int = _messageField.text.indexOf(text, offset);
			while (index != -1)
			{
				var left:Number = _messageField.getCharBoundaries(index).left + _messageField.x;
				var right:Number = _messageField.getCharBoundaries(index + text.length - 1).right + _messageField.x;
				graphics.drawRect(left, 2, right - left, 12);
				
				offset = index + text.length;
				index = _messageField.text.indexOf(text, offset);
			}
			graphics.endFill();
		}
		
		private function handleContextMenuItemSelect(event:ContextMenuEvent):void
		{
			System.setClipboard(_data.original.text);
		}
		
		private function handleClick(event:MouseEvent):void
		{
			if (_data.isOpen)
			{
				_data.close();
			}
			else
			{
				_data.open();
			}
			dispatchEvent(new UIEvent(UIEvent.UPDATE, true));
		}
	}
}
